import requests
import ssl
import asyncio
import math
from spider.config.config import url_config
from spider.decorator import need_login
from spider.utils.BaseRequest import BaseRequest
from spider.utils.Looper import Looper

ssl._create_default_https_context = ssl._create_unverified_context

# 禁用安全请求警告
requests.packages.urllib3.disable_warnings()


class Weibo(BaseRequest):
    def __init__(self):
        super().__init__()
        self.user_id = None
        self.looper = Looper()
        self.searchMap = dict()

    def login_weibo(self):
        if self.user_id is None:
            url_obj = url_config.get_login_url()
            resp = self.send_request(url_obj)
            result = resp.json()
            self.user_id = result['data']['uid']

    @need_login
    def search_keyword(self, keyword):
        url_obj = url_config.get_search_url(keyword)
        resp = self.send_request(url_obj)
        result = None
        if resp.status_code == 200:
            result = resp.json()
            if result['ok'] == 1:
                result = result['data']
        if result:
            total = self.get_total(result)
            blog_card = self.get_result_blog(result)
            # print('blog_card', len(blog_card))
            # print('blog_card', blog_card)

            def test_filter(_):
                return _.get('comment_count') > 40
            test_blog_list = list(filter(test_filter, blog_card))

            current_blog = test_blog_list[0]
            print(current_blog)
            self.get_blog_comment(current_blog)
            # ddd = self.get_page_comment_fn(current_blog.get('id'), 1)
            # print(ddd)
        # print('result', result)

    def get_blog_comment(self, blog_dict):
        blog_id = blog_dict.get('id')
        comment_count = blog_dict.get('comment_count')
        max_page = math.ceil(comment_count / 10)
        page_arr = []
        if max_page > 0:
            page_arr = list(range(1, max_page + 1))
        comment_tasks = [asyncio.ensure_future(self.get_comment_by_page(blog_id, _)) for _ in page_arr]
        try:
            self.looper.run(asyncio.wait(comment_tasks))
            result_arr = [_.result() for _ in comment_tasks]
            print('1', result_arr)
        except Exception:
            print('exit', Exception.__str__())
    async def get_comment_by_page(self, blog_id, page):
        result = await self.looper.loop.run_in_executor(None, self.get_page_comment_fn, blog_id, page)
        return result

    def get_page_comment_fn(self, blog_id, page):
        url_obj = url_config.get_comment_url(blog_id, page)
        resp = self.send_request(url_obj)
        resp_data = dict()
        try:
            resp_data = resp.json()
        except Exception as e:
            pass
        if resp.status_code == 200 and resp_data.get('ok', None) == 1:
            return resp_data.get('data', None).get('data', [])
        return []

    @staticmethod
    def get_total(search_result):
        total = 0
        if search_result.get('cardlistInfo', None):
            total = search_result.get('cardlistInfo').get('total')
        return total

    @staticmethod
    def get_result_blog(search_result):
        def filter_card(_):
            return _.get('card_type_name', None) == '微博' and _.get('mblog', None)
        cards = []
        for card in search_result.get('cards', []):
            cards += card.get('card_group')
        blog_cards = list(filter(filter_card, cards))
        return [{
            'id': _.get('mblog').get('id'),
            'comment_count': _.get('mblog').get('comments_count')
        } for _ in blog_cards]

    def get_all_blog(self, cid):
        return
        get_number_future = asyncio.ensure_future(self.get_blog_list_by_page(cid, 1))
        self.looper.run(get_number_future)
        result_number = get_number_future.result()
        page_arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
        tasks = [asyncio.ensure_future(self.get_blog_list_by_page(cid, _)) for _ in page_arr]
        try:
            self.looper.run(asyncio.wait(tasks))
            result_arr = [_.result() for _ in tasks]
            print(result_arr)
        except Exception:
            print('exit', Exception.__str__())
        # cor = self.get_blog_list_by_page(cid, 1)
        # future = asyncio.ensure_future(cor)
        # self.looper.run(future)
        # print(future.result())

    async def get_blog_list_by_page(self, cid, page):
        result = await self.looper.loop.run_in_executor(None, self.get_page_blog_fn, cid, page)
        return result

    def get_page_blog_fn(self, cid, page):
        url_obj = url_config.get_blogs_url(cid, page)
        resp = self.send_request(url_obj)
        return resp.json().get('ok')

    def get_blog_number(self):
        pass





